<?php
class NewProofreadSend
{
    private $id;
    private $dataArray;
    private $dbHandle;
    private $logObject;
    private $checkVideoViStatus;
	private $sendProofreadResult;

	private $audit_log_id;
    private $operationUser;

    public function getProofread($dbHandle, $type, $id, $audit_log_id=0, $send_proofread_result = TRUE, $publish_type = '00')/*{{{*/
    {
		$this->audit_log_id =   $audit_log_id;
        $this->operationUser=   CommonUtils::get_user();

        $this->dbHandle =   $dbHandle;
        $this->id       =   $id;
        $this->logObject=   TRUE;
		$this->sendProofreadResult = $send_proofread_result;

		$this->change_log_all = array();
		$this->dataArray = array();

        $proof_type = $type = strtolower($type);
        if ('episode' == $type || 'programme' == $type) {
			$type = $type.'Send';
		}

		try {
			switch ($publish_type) {
				case 'old': //non-premium -> old flow
				case 'oldold': //all -> old flow
					return;
					break;

				case 'oldnew': //non-premiun -> old flow, premium -> new flow
					$all_new_flow = FALSE;
					$premium = TRUE;
					$this->proof_type = 'p_' . $proof_type;
					$this->$type($id, $premium);
					$this->sendToMq($premium);
					break;

				case 'new':  //non-premium -> new flow
					$all_new_flow = TRUE;
					$this->proof_type = $proof_type;
					$this->$type($id, FALSE);
					$this->sendToMq();
					break;

				case 'newold': //non-premium -> new flow, premium -> old flow
					$all_new_flow = FALSE;
					$this->proof_type = $proof_type;
					$this->$type($id, FALSE);
					$this->sendToMq();
					break;

				case 'newnew': //all go new flow
					$all_new_flow = TRUE;

					$this->proof_type = $proof_type;
					$this->$type($id, FALSE);
					$this->sendToMq();

					$premium = TRUE;
					$this->proof_type = 'p_' . $proof_type;
					$this->$type($id, $premium);
					$this->sendToMq($premium);
					break;
			}

			$this->setChangelogPublished($all_new_flow);

			return TRUE; 
		} catch (Stomp_Exception $e) { 
			mail(CommonUtils::getAdminMail(),"Proofread($type,$id,$audit_log_id):MQ Server Error, At ".trim(`hostname`) , print_r($e,1));
			Model::updateBySql('update audit_log set action=:action where id=:id',array(':action'=>AC::LOG_OP_PUBLISH_FAILED,':id'=>$audit_log_id));
			return FALSE;
		} catch (PDOException $e) {
			mail(CommonUtils::getAdminMail(),"Proofread($type,$id,$audit_log_id):PDOException, At ".trim(`hostname`) , print_r($e,1));
			return;
		} catch (Exception $e) {
			return '0' . $e->getCode();
		}
    }

	/*
	 * by donald
	 */
    public function programmeSend($id, $premium = FALSE)
    {
		$this->change_log = array();
		$this->programme_id = $id;
		$this->episode_id = 0;
		$programme = new programme;
		$programme_detail = $programme->get($id);

        if (AC::STATUS_DELETED  ==  $programme_detail->status) {
			throw new Exception('Programme is deleted.', '0203');
        }

		// video should be ready
		$check_video = $this->checkVideoStatus($programme_detail->folders);
		if (!empty($check_video)) {
			throw new Exception("The programme's video is not readey.", '0202');
		}

        $this->dataArray = array(
			'programme'                 => array(),
			'programme-language'        => array(),
			'programme-tvbcom_category' => array(),
			'programme_cpl'             => array(),
			'programme_premium'         => array(),
			'programme_ppv'             => array(),
			'programme_subscription'    => array(),
			'tag'                       => array(),
			'folder'                    => array(),
			'folder-language'           => array(),
			'folder_item'               => array(),
			'folder_item-language'      => array(),
			'image'                     => array(),
			'image-language'            => array(),
			'image_folder-config'       => array(),
			'video'                     => array(),
			'video-language'            => array(),
			'video_export'              => array(),
			'video_premium'             => array(),
			'video_ppv'              	=> array(),
			'video_subscription'        => array(),
			'cast'                      => array(),
			'cast-language'             => array(),
            'cast_dictionary'           => array(),
			'episode' 					=> array(),
			'episode-language' 			=> array(),
			'episode-video'             => array(),
		);

		if (empty($premium)) {
			unset($this->dataArray['programme_premium']);
			unset($this->dataArray['programme_ppv']);
			unset($this->dataArray['programme_subscription']);
			unset($this->dataArray['video_premium']);
			unset($this->dataArray['video_ppv']);
			unset($this->dataArray['video_subscription']);
		}

		$tables = array_keys($this->dataArray);

		$change_log_list = change_log::get(
			array(
				'is_publish' => 0,
				'programme_id' => $id,
			)
		);

		if (empty($change_log_list)) {
			return;
		}

		$delete_sql = $this->getDeleteSql($change_log_list, $premium);
		if (!empty($delete_sql)) {
			$this->dataArray['delete_sql'] = $delete_sql; 
		}

		foreach ($change_log_list as $change_log) {
			// is delete
			if (empty($change_log['is_active'])) {
				$this->change_log[] = $change_log;
				continue;
			}

			$table = $change_log['type'];

			if (!in_array($table, $tables)) {
				continue;
			}	

			switch ($table) {
				case 'programme':
				case 'programme-language':
				case 'programme-tvbcom_category':
				case 'programme_cpl':
				case 'programme_premium':
				case 'programme_ppv':
				case 'programme_subscription':
					$class_name = str_replace('-', '_', $table);
					$table_object = new $class_name;

					# modify by vanni for bug 7327
					# Need keep param order like as model::getPrimaryKey order
					#$table_detail = $table_object->get($change_log['keys']);
					if('programme' == $table){                      # primaryKey is: array('id')
						$primary_val = array(
							$change_log['keys']['id']
						);
					}elseif('programme-tvbcom_category' == $table){ # primaryKey is: array('programme_id', 'category_id')
						$primary_val = array(
							$change_log['keys']['programme_id'],
							$change_log['keys']['category_id']
						);
					}elseif('programme-language' == $table){        # primaryKey is: array('programme_id', 'language_id')
						$primary_val = array(
							$change_log['keys']['programme_id'],
							$change_log['keys']['language_id']
						);
					}elseif('programme_cpl' == $table){             # primaryKey is: array('programme_id', 'effective_date')
						$primary_val = array(
							$change_log['keys']['programme_id'],
							$change_log['keys']['effective_date']
						);
					}else{                                          # primaryKey is: array('programme_id')
						$primary_val = array(
							$change_log['keys']['programme_id']
						);
					}
					$table_detail = $table_object->get($primary_val);

					$table_detail = Model::object2array($table_detail);
					$this->dataArray[$table][] = $table_detail; 
					$this->change_log[] = $change_log;
					break;
				
				case 'video':
					$this->video($change_log['keys']['id'], $premium);
					break;

				case 'image':
					$this->image($change_log['keys']['id']);
					$this->change_log[] = $change_log;
					break;

				case 'cast':
					$this->cast($change_log['keys']['id']);
					$this->change_log[] = $change_log;
					break;

				case 'folder':
					$this->folder($change_log['keys']['id']);
					$this->change_log[] = $change_log;
					break;

				case 'folder_item':
					$this->folder_item($change_log, $premium);
					break;

				case 'folder-language':
				case 'folder_item-language':
				case 'video-language':
				case 'video_export':
				case 'episode':
				case 'episode-language':
				case 'episode-video':
				case 'image-language':
				case 'cast-language':
				case 'cast_dictionary':
				case 'tag':
					break;
				default:
					break;
			}
		}
		
		$this->getTagByProgramme();
    }

	/*
	 * by donald
	 */
    private function episodeSend($id, $premium)
    {
		$this->change_log = array();
		$episode = new episode;
		$episode_detail = $episode->get($id);

		$this->programme_id = $episode_detail->programme_id;
		$this->episode_id = $id;

		$publish_log_list = publish_log::getPublishLog('programme', $episode_detail->programme_id);

		if (empty($publish_log_list) ||
			($this->proof_type == 'episode' && empty($publish_log_list->non_premium)) ||
			($this->proof_type == 'episode' && $publish_log_list->non_premium->status != AC::STATUS_PUBLISH) ||
			($this->proof_type == 'p_episode' && empty($publish_log_list->premium)) ||
			($this->proof_type == 'p_episode' && $publish_log_list->premium->status != AC::STATUS_PUBLISH_PREMIUM)) {
			throw new Exception("The episode's programme is not published.", '0201');
		} 

        $this->dataArray = array(
			'episode'                   => array(),
			'episode-language'          => array(),
			'tag'                       => array(),
			'folder'                    => array(),
			'folder-language'           => array(),
			'folder_item'               => array(),
			'folder_item-language'      => array(),
			'image'                     => array(),
			'image-language'            => array(),
			'image_folder-config'       => array(),
			'info_address'              => array(),
			'info_award'                => array(),
			'info_biography'            => array(),
			'info_general_information'  => array(),
			'info_pageant'				=> array(),
			'info_product'              => array(),
			'info_q_a'                  => array(),
			'info_recipe'               => array(),
			'info_song'                 => array(),
			'cast'                      => array(),
			'cast-language'             => array(),
            'cast_dictionary'           => array(),
		);

		$tables = array_keys($this->dataArray);

		$change_log_list = change_log::get(
			array(
				'is_publish' => 0,
			   	'episode_id' => $id 
			)
		);

		if (empty($change_log_list)) {
			return;
		}

		$delete_sql = $this->getDeleteSql($change_log_list, $premium);
		if (!empty($delete_sql)) {
			$this->dataArray['delete_sql'] = $delete_sql; 
		}

		foreach ($change_log_list as $change_log) {
			// is delete
			if (empty($change_log['is_active'])) {
				$this->change_log[] = $change_log;
				continue;
			}

			$table = $change_log['type'];

			if (!in_array($table, $tables)) {
				continue;
			}	

			switch ($table) {
				case 'episode':
				case 'episode-language':
				case 'info_address':
				case 'info_award':
				case 'info_biography':
				case 'info_general_information':
				case 'info_pageant':
				case 'info_product':
				case 'info_q_a':
				case 'info_recipe':
				case 'info_song':
					$class_name = str_replace('-', '_', $table);
					$table_object = new $class_name;

					# modify by vanni for bug 7327
					# Need keep param order like as model::getPrimaryKey order
					#$table_detail = $table_object->get($change_log['keys']);
					if('episode-language' == $table){              # primaryKey is: array('episode_id','language_id')
						$primary_val = array(
							$change_log['keys']['episode_id'],
							$change_log['keys']['language_id']
						);
					}else{                                         # primaryKey is: array('id')
						$primary_val = array(
							$change_log['keys']['id']
						);
					}
					$table_detail = $table_object->get($primary_val);

					$table_detail = Model::object2array($table_detail);
					$this->dataArray[$table][] = $table_detail; 
					$this->change_log[] = $change_log;
					break;

				case 'image':
					$this->image($change_log['keys']['id']);
					$this->change_log[] = $change_log;
					break;

				case 'cast':
					$this->cast($change_log['keys']['id']);
					$this->change_log[] = $change_log;
					break;

				case 'folder':
					$this->folder($change_log['keys']['id']);
					$this->change_log[] = $change_log;
					break;

				case 'folder_item':
					$this->folder_item($change_log, FALSE);
					break;

				case 'folder-language':
				case 'folder_item-language':
				case 'tag':
				case 'image-language':
				case 'image_folder-config':
				case 'cast-language':
				case 'cast_dictionary':
					break;

				default:
					break;
			}
		}
	
		$this->getTagByEpisode();
    }

	/*
	 * by donald
	 */
	public function folder($folder_id)
	{
		if (empty($folder_id)) {
			return;
		}

		$folder = new folder;
		$folder_detail = $folder->get($folder_id);
		$this->dataArray['folder'][] = Model::object2array($folder_detail);

		$folder_language = new folder_language;
		$folder_language_list = $folder_language->getAll(
			array(
				'folder_id' => $folder_id
			)
		);

		foreach ($folder_language_list as $folder_language) {
			$this->dataArray['folder-language'][] = Model::object2array($folder_language);
		}

		$language_list = language::getAll();
		foreach ($language_list as $language) {
			$change_log_detail = change_log::get(
				array(
					'type' => $folder_language->getTableName(),
					'keys' => array(
						'folder_id' => $folder_id,
						'language_id' => $language->id, 
					)
				)
			);

			if (!empty($change_log_detail)) {
				$this->change_log[] = $change_log_detail[0];
			} 
		}

		$this->image_folder_config($folder_id);
	}

	/*
	 * by donald
	 */
	public function folder_item($change_log, $premium = FALSE)
	{
		$folder_id = $change_log['keys']['folder_id'];
		$item_id = $change_log['keys']['item_id'];

		$folder = new folder;
		$folder_detail = $folder->get($folder_id);

		if ($premium && $folder_detail->folder_item_type_id == AC::FOLDER_TYPE_VIDEO) {
			$video = new video;
			$video_detail = $video->get($item_id);
			if (empty($video_detail->premium_flag)) {
				return;
			}
		}

		$folder_item = new folder_item;

		# modify by vanni for bug 7327
		# Need keep param order like as folder_item::getPrimaryKey order
		#$folder_item = $folder_item->get($change_log['keys']);
		$folder_item = $folder_item->get(array($change_log['keys']['folder_id'],$change_log['keys']['item_id']));

		$this->dataArray['folder_item'][] = Model::object2array($folder_item);
		$this->change_log[] = $change_log;

		$folder_item_language = new folder_item_language;
		$folder_item_language_list = $folder_item_language->getAll(
			array(
				'folder_id' => $folder_id,
				'item_id' => $item_id
			)
		);

		foreach ($folder_item_language_list as $folder_item_language) {
			$this->dataArray['folder_item-language'][] = Model::object2array($folder_item_language);
		}

		$language_list = language::getAll();
		foreach ($language_list as $language) {
			$change_log_detail = change_log::get(
				array(
					'type' => $folder_item_language->getTableName(),
					'keys' => array(
						'folder_id' => $folder_id, 
						'item_id' => $item_id,
						'language_id' => $language->id 
					)
				)
			);

			if (!empty($change_log_detail)) {
				$this->change_log[] = $change_log_detail[0];
			} 

			// bug 7307
			$change_log_detail = change_log::get(
				array(
					'type' => $folder_item_language->getTableName(),
					'keys' => array(
						'item_id' => $item_id,
						'folder_id' => $folder_id, 
						'language_id' => $language->id 
					)
				)
			);

			if (!empty($change_log_detail)) {
				$this->change_log[] = $change_log_detail[0];
			} 
		}
	}

	/*
	 * by donald
	 */
    private function cast($cast_id)
    {
		if (empty($cast_id)) { 
			return; 
		}

		$cast = new cast;
		$cast_detail = $cast->get($cast_id);
		$this->dataArray['cast'][] = Model::object2array($cast_detail);

		$cast_language = new cast_language;
		$cast_language_list = $cast_language->getAll($cast_id);
		foreach ($cast_language_list as $cast_language) {
			$this->dataArray['cast-language'][] = Model::object2array($cast_language);
		}

		$language_list = language::getAll();
		foreach ($language_list as $language) {
			$change_log_detail = change_log::get(
				array(
					'type' => $cast_language->getTableName(),
					'keys' => array(
						'cast_id' => $cast_id,
						'language_id' => $language->id
					)
				)
			);

			if (!empty($change_log_detail)) {
				$this->change_log[] = $change_log_detail[0];
			} 
		}

		$this->getTag($cast_detail->tags);
    }

    /*
     * by donald 
     */
	public function image_folder_config($folder_id)
	{
		if (empty($folder_id)) {
			return;
		}

		$change_log_detail = change_log::get(
			array(
				'type' => 'image_folder-config',
				'keys' => array(
					'folder_id' => $folder_id
				)
			)
		);

		if (empty($change_log_detail)) {
			return;
		}

		$image_folder_config = new image_folder_config;
		$image_folder_config = $image_folder_config->get($folder_id);
		if (!empty($image_folder_config)) {
			$this->dataArray['image_folder-config'][] = Model::object2array($image_folder_config);
			$this->change_log[] = $change_log_detail[0];
		}	
	}

	/*
	 * by donald
	 */
    private function getCastDictionary($ids)
    {
        if (empty($ids)) {
            return; 
        }

		$ids = explode(',', $ids);

		foreach ($ids as $id) {
			$this->cast_dictionary($id);
		}
    }

	/*
	 * by donald
	 */
	public function cast_dictionary($id)
	{
		if (empty($id)) {
			return;
		}

		$change_log_detail = change_log::get(
			array(
				'type' => 'cast_dictionary',
				'keys' => array(
					'id' => $id 
				)
			)
		);

		if (empty($change_log_detail)) {
			return;
		}

		$cast_dictionary = new cast_dictionary;
		$cast_dictionary_detail = $cast_dictionary->get($id);
		if (!empty($cast_dictionary_detail)) {
			$this->dataArray['cast_dictionary'][] = Model::object2array($cast_dictionary_detail);
			$this->change_log[] = $change_log_detail[0];
		}
	}

	/*
	 * by donald
	 */
	public function getTagByProgramme()
	{
		if (!empty($this->dataArray['programme'][0]['tags'])) {
			$this->getTag($this->dataArray['programme'][0]['tags']);
		}
	}

	/*
	 * by donald
	 */
	public function getTagByEpisode()
	{
		if (!empty($this->dataArray['episode'][0]['tags'])) {
			$this->getTag($this->dataArray['episode'][0]['tags']);
		}
	}

    private function checkVideoStatus($folders)
    {
        if (empty($folders))    $folders    =   '""'; 

        $sql=   '
            SELECT
                fi.item_id      AS  itemID
            FROM
                folder      AS  f,
                folder_item AS  fi,
                video       AS  v
            WHERE
                f.id = fi.folder_id
                AND v.id = fi.item_id
                AND v.vi_status <> "'. AC::VIDEO_STATUS_UPLOADED. '"
                AND v.status <>"'. AC::STATUS_DELETED. '"
                AND f.folder_item_type_id = "'.AC::FOLDER_TYPE_VIDEO. '"
				AND f.folder_type_id = "'.AC::VIDEO_CATCHUP.'"
                AND f.id IN ('. $folders .')
            Limit 1
            ';
        $result =   CommonUtils::exec_sql($this->dbHandle, $sql);
        return  empty($result[0]['itemID']) ?   NULL    :   $result;
    }


    private function sendToMq($premium = FALSE)
    {
		if (empty($this->change_log)) {
			return;
		}

		if (empty($premium)) {
			$name = 'ProofreadSend';
		} else {
			$name = 'P_ProofreadSend';
		}

        if (empty($this->dataArray) ||  !is_array($this->dataArray))    return  NULL;
		$config = ConfigReaderFactory::getInstance()->getConfigReader(AC::CONFIG_MQ)->getConfig();
		$consumerConfig = $config->xpath("/config/consumer[@name='" . $name . "']");

		$broker = (string) $consumerConfig[0]->broker;
		$queue  = (string) $consumerConfig[0]->queue;

		$this->dataArray['proof_type'] = $this->proof_type;
		$this->dataArray['programme_id'] = $this->programme_id;
		$this->dataArray['episode_id'] = $this->episode_id;
		$this->dataArray['audit_log_id']=$this->audit_log_id;
		$this->dataArray['operationUser']=$this->operationUser;
		$this->dataArray['sendProofreadResult'] = $this->sendProofreadResult;
		$this->dataArray['change_log'] = $this->change_log;

		if ($premium) {
			file_put_contents('/tmp/p_proofread_change_log', var_export($this->change_log, TRUE));
		} else {
			file_put_contents('/tmp/proofread_change_log', var_export($this->change_log, TRUE));
		}

		foreach ($this->change_log as $change_log) {
			array_push($this->change_log_all, $change_log);
		}
		$this->change_log = array();

		return MessageHelper::sendMessage($broker, $queue, $this->dataArray);
	}

    /**
	 * by donald
     */
	public function getChapter($video_id)
	{
        $chapter = new chapter();
        $ids = $chapter->getChapterIDByVideoID($video_id);
        if (!empty($ids)) {
            $ids = explode(',', $ids);

			foreach ($ids as $chapter_id) {
				$this->chapter($chapter_id);
			}
        }
	}

	/*
	 * by donald
	 */
    public function getTag($ids)
    {
		if (empty($ids)) {
			return;
		}

		$ids = explode(',', $ids);
		
		foreach ($ids as $tag_id) {
			$this->tag($tag_id);
		}
    }

	/*
	 * by donald
	 */
    public function image($id)
    {
		if (empty($id)) {
			return;
		}

		$image = new image;
		$image_detail = $image->get($id);
		$this->dataArray['image'][] = Model::object2array($image_detail);

		$image_language = new image_language;
		$image_language_list = $image_language->getAll($id);
		foreach ($image_language_list as $image_language_detail) {
			$this->dataArray[$image_language->getTableName()][] = Model::object2array($image_language_detail);
		}

		$language_list = language::getAll();
		foreach ($language_list as $language) {
			$change_log_detail = change_log::get(
				array(
					'type' => $image_language->getTableName(),
					'keys' => array(
						'image_id' => $id, 
						'language_id' => $language->id 
					)
				)
			);

			if (!empty($change_log_detail)) {
				$this->change_log[] = $change_log_detail[0];
			} 
		}

        $this->getCastDictionary($image_detail->casts);
		$this->getTag($image_detail->tags);
    }

	/*
	 * by donald
	 */
    public function video($video_id, $premium = FALSE)
    {
		$video = new video;
		$video_detail = $video->get($video_id);

		if ($premium && empty($video_detail->premium_flag)) {
			return;
		}

		$this->dataArray['video'][] = Model::object2array($video_detail);

		$change_log_detail = change_log::get(
			array(
				'type' => $video_detail->getTableName(),
				'keys' => array('id' => $video_detail->id),
			)
		);

		if (!empty($change_log_detail)) {
			$this->change_log[] = $change_log_detail[0];
		}

		$video_language = new video_language;
		$video_language_list = $video_language->getAll($video_id);
		foreach ($video_language_list as $video_language_detail) {
			$this->dataArray['video-language'][] = Model::object2array($video_language_detail);
		}

		$language_list = language::getAll();
		foreach ($language_list as $language) {
			$change_log_detail = change_log::get(
				array(
					'type' => $video_language->getTableName(),
					'keys' => array(
						'video_id' => $video_id, 
						'language_id' => $language->id 
					)	
				)
			);

			if (!empty($change_log_detail)) {
				$this->change_log[] = $change_log_detail[0];
			}
		}
	
		$video_export = new video_export;
		$video_export_list = $video_export->getAll($video_id);
		foreach ($video_export_list as $video_export_detail) {
			$this->dataArray['video_export'][] = Model::object2array($video_export_detail);

			$change_log_detail = change_log::get(
				array(
					'type' => $video_export_detail->getTableName(),
					'keys' => array('id' => $video_export_detail->id),
				)
			);

			if (!empty($change_log_detail)) {
				$this->change_log[] = $change_log_detail[0];
			}
		}

		$episode_video = new episode_video;
		$episode_video_list = $episode_video->getAll(array('video_id' => $video_id));
		foreach ($episode_video_list as $episode_video_detail) {
			if ($premium) {
				$publish_log_detail = publish_log::getPremiumPublishLog('episode', $episode_video_detail->episode_id);
			} else {
				$publish_log_detail = publish_log::getNonPremiumPublishLog('episode', $episode_video_detail->episode_id);
			}

			if (empty($publish_log_detail) || (empty($premium) && $publish_log_detail->status == AC::STATUS_UNPUBLISH) || ($premium && $publish_log_detail->status == AC::STATUS_UNPUBLISH_PREMIUM)) {
				$episode = new episode;
				$episode_detail = $episode->get($episode_video_detail->episode_id);
				$episode_detail->status = AC::STATUS_HIBERNATE;
				$this->dataArray['episode'][] = Model::object2array($episode_detail);

				$episode_language = new episode_language;
				$episode_language_list = $episode_language->getAll($episode_video_detail->episode_id);
				foreach ($episode_language_list as $episode_language_detail) {
					$this->dataArray['episode-language'][] = Model::object2array($episode_language_detail);
				}
			}

			$this->dataArray['episode-video'][] = Model::object2array($episode_video_detail);

			$change_log_detail = change_log::get(
				array(
					'type' => $episode_video_detail->getTableName(),
					'keys' => array(
						'episode_id' => $episode_video_detail->episode_id,
						'video_id' => $episode_video_detail->video_id
					)
				)
			);

			if (!empty($change_log_detail)) {
				$this->change_log[] = $change_log_detail[0];
			}

			$change_log_detail = change_log::get(
				array(
					'type' => $episode_video_detail->getTableName(),
					'keys' => array(
						'video_id' => $episode_video_detail->video_id,
						'episode_id' => $episode_video_detail->episode_id,
					)
				)
			);

			if (!empty($change_log_detail)) {
				$this->change_log[] = $change_log_detail[0];
			}

		}

        $this->getCastDictionary($video_detail->casts);
		$this->getTag($video_detail->tags);
		$this->getChapter($video_id);

		if ($premium && $video_detail->premium_flag) {
			$video_premium = new video_premium;
			$video_premium_detail = $video_premium->get($video_id);
			$this->dataArray['video_premium'][] = Model::object2array($video_premium_detail);

			$change_log_detail = change_log::get(
				array(
					'type' => $video_premium_detail->getTableName(),
					'keys' => array(
						'video_id' => $video_premium_detail->video_id
					)
				)
			);

			if (!empty($change_log_detail)) {
				$this->change_log[] = $change_log_detail[0];
			}

			if ($video_premium_detail->ppv_flag) {
				$video_ppv_detail = video_ppv::getOne($video_id);
				$this->dataArray['video_ppv'][] = Model::object2array($video_ppv_detail);

				$change_log_detail = change_log::get(
					array(
						'type' => $video_ppv_detail->getTableName(),
						'keys' => array(
							'video_id' => $video_ppv_detail->video_id
						)
					)
				);

				if (!empty($change_log_detail)) {
					$this->change_log[] = $change_log_detail[0];
				}
			}

			if ($video_premium_detail->subscription_flag) {
				$video_subscription_detail = video_subscription::getOne($video_id);
				$this->dataArray['video_subscription'][] = Model::object2array($video_subscription_detail);

				$change_log_detail = change_log::get(
					array(
						'type' => $video_subscription_detail->getTableName(),
						'keys' => array('video_id' => $video_subscription_detail->video_id)
					) 
				);

				if (!empty($change_log_detail)) {
					$this->change_log[] = $change_log_detail[0];
				}
			}
		}
    }

	/*
	 * by donald
	 */
	public function tag($id)
	{
		if (empty($id)) {
			return;
		}

		$change_log_detail = change_log::get(
			array(
				'type' => 'tag',
				'keys' => array('id' => $id)
			)
		);

		if (empty($change_log_detail)) {
			return;
		}

		$tag = new tag;
		$tag_detail = $tag->get($id);
		$this->dataArray['tag'][] = Model::object2array($tag_detail);
		$this->change_log[] = $change_log_detail[0];
	}

	/*
	 * by donald
	 */
    public function chapter($id)
    {
		$chapter = new chapter;
		$chapter_detail = $chapter->get($id);
		if ($chapter_detail->status == AC::STATUS_DELETED) {
			return;
		}

		$this->dataArray['chapter'][] = Model::object2array($chapter_detail);

		$change_log_detail = change_log::get(
			array(
				'type' => $chapter_detail->getTableName(),
				'keys' => array(
					'id' => $chapter_detail->id
				)
			)
		);

		if (!empty($change_log_detail)) {
			$this->change_log[] = $change_log_detail[0];
		}

		$chapter_language = new chapter_language;
		$chapter_language_list = $chapter_language->getAll(array('chapter_id' => $id)); 
		foreach ($chapter_language_list as $chapter_language_detail) {
			$this->dataArray['chapter-language'][] = Model::object2array($chapter_language_detail);
		}

		$language_list = language::getAll();
		foreach ($language_list as $language) {
			$change_log_detail = change_log::get(
				array(
					'type' => $chapter_language->getTableName(),
					'keys' => array(
						'chapter_id' => $id, 
						'language_id' => $language->id 
					)
				)
			);

			if (!empty($change_log_detail)) {
				$this->change_log[] = $change_log_detail[0];
			}
		}

		$chapter_tvbcom_category = new chapter_tvbcom_category;
		$chapter_tvbcom_category_list = $chapter_tvbcom_category->getAll($id);
		foreach ($chapter_tvbcom_category_list as $chapter_tvbcom_category) {
			$this->dataArray['chapter-tvbcom_category'][] = Model::object2array($chapter_tvbcom_category);

			$change_log_detail = change_log::get(
				array(
					'type' => $chapter_tvbcom_category->getTableName(),
					'keys' => array(
						'chapter_id' => $chapter_tvbcom_category->chapter_id,
						'category_id' => $chapter_tvbcom_category->category_id,
					)
				)
			);

			if (!empty($change_log_detail)) {
				$this->change_log[] = $change_log_detail[0];
			}
		}

        $this->getCastDictionary($chapter_detail->casts);
		$this->getTag($chapter_detail->tags);
    }

	/*
	 * by donald
	 */
	public static function getDeleteSQL($change_log_list, $premium)
	{
		if (empty($change_log_list)) {
			return;
		}

		$delete_sql = array();
		$list = array(
			'episode' => array(),
			'chapter-tvbcom_category' => array(),
			'programme-tvbcom_category' => array(),
			'programme_cpl' => array(),
			'folder' => array(),
			'folder-language' => array(),
			'folder_item' => array(),
			'folder_item-language' => array(),
			'image' => array(),
			'image-language' => array(),
			'video' => array(),
			'video-language' => array(),
			'video_premium' => array(),
			'video_subscription' => array(),
			'video_export' => array(),
			'episode-video' => array(),
			'image_folder-config' => array(),
		);

		foreach ($change_log_list as $change_log) {
			// is delete
			if (empty($change_log['is_active'])) {
				$list[$change_log['type']][] = self::deleteSql($change_log, $premium);
				continue;
			}
		}

		foreach ($list as $table => $querys) {
			if (!empty($querys)) {
				foreach ($querys as $query) {
					$delete_sql[] = $query;
				}
			}
		}
		
		return $delete_sql;
	}

	/*
	 * by donald
	 */
	public static function deleteSql($change_log, $premium)
	{
		$table_name = $premium ? ('p_'. $change_log['type']) : $change_log['type'];

		foreach ($change_log['keys'] as $key => $value) {
			$where[] = $key . " = '" . $value . "'";
		}

		return 'DELETE FROM `' . $table_name . '` WHERE ' . implode(' AND ', $where);
	}

	/*
	 * by donald
	 */
	public function setChangelogPublished($new_flow)
	{
		if (empty($this->change_log_all)) {
			if ($new_flow) {
				throw new Exception('No need proofread again because nothing is changed.', '0207');
			} else {
				return;
			}
		}

		foreach ($this->change_log_all as $change_log) {
			$all[] = json_encode($change_log);
		}

		$all = array_unique($all);
	
		foreach ($all as $value) {
			$all_unique[] = json_decode($value, TRUE);
		}

		change_log::setIsPublishByArray($all_unique);
	}
}
?>
